package com.ch3cooh.rpc.component;

import com.ch3cooh.registry.pojo.RegisterInfo;
import com.ch3cooh.registry.service.RegisterService;
import com.ch3cooh.rpc.pojo.ControllerInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @功能:每个服务内部自己维护的 服务信息表
 * @作者:chanson
 * @时间:2018/4/29 22:36
 */
@Component
public class LocalServerManager {

    /* 使用concurrentHashMao来维护 信息*/
    private ConcurrentHashMap<String , List<ControllerInfo>> serviceMap = new ConcurrentHashMap<>();

    public ConcurrentHashMap showAll(){
        return serviceMap;
    }

    public void sync(Map<String,List<ControllerInfo>> map){
        Set<Map.Entry<String, List<ControllerInfo>>> entries = map.entrySet();
        for(Map.Entry<String,List<ControllerInfo>> e : entries){
            serviceMap.put(e.getKey(),e.getValue());
        }
    }

    public  String getHttpHostUrl(String serviceName){
        //TODO: 这里还可以用到负载均衡算法， 这里默认调用[0]下标的服务
        List<ControllerInfo> controllerInfos = serviceMap.get(serviceName);
        if(controllerInfos != null && controllerInfos.size() > 0){
            return controllerInfos.get(0).getHttpHostUrl();
        }
        return "";
    }

    /**
     * 向服务代理中添加 所有在注册中心注册过的服务信息
     * @param info
     */
    public void addService(RegisterInfo info){
        String serverName = info.getServerName();
        List<ControllerInfo> controllerInfoList = serviceMap.get(serverName);
        if(controllerInfoList == null){
            controllerInfoList = new ArrayList<>();
            serviceMap.put(info.getServerName() , controllerInfoList);
        }
        controllerInfoList.add( changeToControllerInfo(info) );

    }

    /**
     * 删除与注册中心断开连接的服务信息
     * @param info
     */
    public void removeService(RegisterInfo info){
        String serverName = info.getServerName();
        List<ControllerInfo> controllerInfoList = serviceMap.get(serverName);
        if( !CollectionUtils.isEmpty(controllerInfoList) ){
            controllerInfoList.remove( changeToControllerInfo(info)  );
            if(controllerInfoList.size() == 0){
                serviceMap.remove(info.getServerName());
            }
        }
    }

    public ControllerInfo changeToControllerInfo(RegisterInfo info){
       return new ControllerInfo(info.getServerName() ,
                info.getHttpHostUrl());
    }


}
